import { defineStore } from "pinia";
import category, { type CategoryData } from "@/api/category";
import { ElMessage } from "element-plus";
import type { AxiosError } from "axios";

// 定义state的返回烈性
interface UserCategoryStoreStateData {
  category1List: CategoryData[];
  category2List: CategoryData[];
  category3List: CategoryData[];
  category1Id: number | string;
  category2Id: number | string;
  category3Id: number | string;
}

export const useCategoryStore = defineStore("category", {
  state(): UserCategoryStoreStateData {
    return {
      category1List: [],
      category2List: [],
      category3List: [],
      category1Id: "",
      category2Id: "",
      category3Id: "",
    };
  },
  actions: {
    // 获取一级分类数据
    async getCategory1List() {
      try {
        const result = await category.getCategory1();
        this.category1List = result;
      } catch (error) {
        ElMessage.error("获取一级分类列表失败" + (error as AxiosError).message);
      }
    },
    // 获取二级分类数据
    async getCategory2List() {
      // 重新选择以及分类清空二三级分类
      this.category2Id = "";
      this.category2List = [];
      this.category3Id = "";
      this.category3List = [];
      try {
        const result = await category.getCategory2(this.category1Id as number);
        this.category2List = result;
      } catch (error) {
        ElMessage.error("获取二级分类列表失败" + (error as AxiosError).message);
      }
    },
    // 获取三级分类数据
    async getCategory3List() {
      // 重新在选择二级分类清空三级分类
      this.category3Id = "";
      this.category3List = [];
      try {
        const result = await category.getCategory3(this.category2Id as number);
        this.category3List = result;
      } catch (error) {
        ElMessage.error("获取三级分类列表失败" + (error as AxiosError).message);
      }
    },
  },
  getters: {},
});
